package com.smap.layer;

import java.util.HashMap;
import java.util.Map;

import com.smap.common.Utils;
import com.smap.common.Utils.HttpCallback;
import com.smap.core.Bbox;

public class WmsLayer extends GridLayer {

	public boolean singleTile = false;
	public String format = "png";
	public String server;
	public String layer;

	public WmsLayer(String server, String layer) {
		super();
		this.server = server;
		this.layer = layer;
	}

	public void draw() {
		if (singleTile) {
			clearScreen();
			Bbox extent = this.map.getExtent(this.width, this.height);

			String url = server
					+ "?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&transparent=true"
					+ "&LAYERS=" + layer + "&SRS="
					+ this.map.getProj().getSRS() + "&BBOX=" + extent
					+ "&WIDTH=" + this.width + "&HEIGHT=" + this.height
					+ "&FORMAT=image/" + this.format;

			drawPicture(url, 0, 0);
		} else {
			super.draw();
		}
	}

	@Override
	public void setUrl(Tile tile) {
		double res = map.getResolution();
		double x = this.minX + (tile.x * tileSize) * res;
		double y = this.minX + (tile.y * tileSize) * res;
		Bbox extent = new Bbox().expand(x, y).expand(x + tileSize * res,
				y + tileSize * res);
		String url = server
				+ "?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&transparent=true"
				+ "&LAYERS=" + layer + "&SRS=" + this.map.getProj().getSRS()
				+ "&BBOX=" + extent + "&WIDTH=" + tileSize + "&HEIGHT="
				+ tileSize + "&FORMAT=image/" + this.format;
		// System.out.println(url);
		tile.imageUrl = url;
	}

	@Override
	public void getInfo(int x, int y, final InfoHandler handler) {
		/*
		 * http://localhost:8000/geoserver/wms
		 * ?bbox=-130,24,-66,50&styles=population
		 * &format=jpeg&info_format=text/plain&request=GetFeatureInfo
		 * &layers=topp
		 * :states&query_layers=topp:states&width=550&height=250&x=170&y=160
		 */

		Map<String, String> params = new HashMap<String, String>();
		params.put("BBOX", this.map.getExtent().toString());
		params.put("INFO_FORMAT", "text/plain");
		params.put("REQUEST", "GetFeatureInfo");
		params.put("LAYERS", layer);
		params.put("QUERY_LAYERS", layer);
		params.put("SRS", this.map.getProj().getSRS());
		// here conver x, y to screen x,y from left-top
		int w = map.getWidth();
		int h = map.getHeight();
		x = x + w / 2;
		y = y + h / 2;
		params.put("WIDTH", w + "");
		params.put("HEIGHT", h + "");
		params.put("X", x + "");
		params.put("Y", y + "");

		String url = server + "?" + Utils.mapToUrl(params);
		Utils.get(url, new HttpCallback() {
			@Override
			public void execute(String ret) {
				handler.execute(ret + "");
			}
		});
	}
}
